package com.szwistar.common.comm;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.mina.filter.ssl.KeyStoreFactory;
import org.apache.mina.filter.ssl.SslContextFactory;

public class SSLContextGenerator {
    /**
     * 这个方法，通过keystore和truststore文件返回一个SSLContext对象
	 * @param keyStoreFile 提供keystore的存放目录，读取keystore的文件内容
	 * @param trustStoreFile 提供truststore的存放目录，读取truststore的文件内容
	 * @param password
     * @return
     */
    public SSLContext getSslContext(File keyStoreFile, File trustStoreFile, String password) {
        try {
            if (!keyStoreFile.exists() || !trustStoreFile.exists()) {
                System.out.println("Keystore or Truststore file does not exist");
                return null;
            }

            KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
            keyStoreFactory.setDataFile(keyStoreFile);
            keyStoreFactory.setPassword(password);
            KeyStore keyStore = keyStoreFactory.newInstance();

            KeyStoreFactory trustStoreFactory = new KeyStoreFactory();
            trustStoreFactory.setDataFile(trustStoreFile);
            trustStoreFactory.setPassword(password);
            KeyStore trustStore = trustStoreFactory.newInstance();

            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyManagerFactoryKeyStore(keyStore);
            sslContextFactory.setTrustManagerFactoryKeyStore(trustStore);
            sslContextFactory.setKeyManagerFactoryKeyStorePassword(password);
            return sslContextFactory.newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 通过证书文件流，创建一个 SSLContext
     * @param certificates
     * @return
     */
    public static TrustManager[] getTrustManagers(InputStream... certificates) {
	    try {
	    	if(certificates != null) {
		        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
		        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		        keyStore.load(null);

		        int index = 0;
		        for (InputStream certificate: certificates) {
		            String certificateAlias = Integer.toString(index++);
		            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
		            try { if(certificate != null) { certificate.close(); } } catch(IOException e) {}
		        }

		        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		        trustManagerFactory.init(keyStore);
		        return trustManagerFactory.getTrustManagers();
	    	} else {
	    		X509TrustManager tm = new X509TrustManager() {
	                @Override
	                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
	                @Override
	                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
	                @Override
	                public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
	            };
		        return new TrustManager[] { tm };
	    	}
	    } catch (Exception e) {
	        e.printStackTrace();
		    return null;
	    }
    }

    /**
     * 通过证书文件流，创建一个 SSLContext
     * @param certificates
     * @return
     */
    public static SSLContext getSslContext(InputStream... certificates) {
	    try {
    	    SSLContext sslContext = SSLContext.getInstance("TLS");
    	    sslContext.init(null, getTrustManagers(certificates), new SecureRandom());
	        return sslContext;
	    } catch (Exception e) {
	        e.printStackTrace();
		    return null;
	    }
    }
}
